'use strict';

var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var cssExtractPlugin = new ExtractTextPlugin('css/style.css?[contenthash:16]');
const merge = require('webpack-merge');

const TARGET = process.env.npm_lifecycle_event;

const PATHS = {
  src: path.join(__dirname, 'app'),
  dist: path.join(__dirname, 'dist')
};

const common = {
  entry: [
    PATHS.src
  ],
  output: {
    path: PATHS.dist,
    filename: 'bundle/bundle.js?[hash]',
    publicPath: '/'
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: PATHS.src+'/assets/index.html'
    }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('dev')
    })
  ],
  resolve: {
      // you can now require('file') instead of require('file.coffee')
      root:[path.resolve(PATHS.src+'/assets')],
      extensions: ['', '.jsx','.js','.scss','.css','.json'],
  },
  module: {
    loaders: [{ test: /\.html$/, loader: "html" },
    {test:/libs\/app/,loader:'imports?jQuery=jquery,$=jquery'},
    { test: /\.(css|scss)$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style", "css!sass")},
    { test: /\.jsx?$/,  exclude: /(node_modules|bower_components)/, loaders: ['babel?cacheDirectory']},
    { test: /\.woff(2)?(\?t=\d+)?$/, loader: "url-loader?name=font/[name].[ext]?[hash]&limit=10000&minetype=application/font-woff" },
    { test: /\.(ttf|eot|svg)(\?t=\d+)?$/, loader: "file-loader?name=font/[name].[ext]?[hash:16]" },
    { test: /\.jpg$/, loader: "file-loader?name=img/[name].[ext]?[hash:16]" },
    { test: /\.png$/, loader: 'url-loader?name=img/[name].[ext]?[hash:16]&limit=8192' }]
  }
};


if(TARGET === 'dev' || !TARGET) {
  module.exports = merge(common, {
    entry: [
      'webpack-hot-middleware/client?reload=true',
      PATHS.src
    ],
    devtool: 'inline-source-map',
    plugins: [
      cssExtractPlugin,
      new HtmlWebpackPlugin({
        template: PATHS.src+'/assets/index.html'
      }),
      new webpack.optimize.OccurenceOrderPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin(),
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('dev')
      })
    ]
  });
}

if(TARGET === 'build' || TARGET === 'production') {
  module.exports = merge(common, {
    plugins:[
      cssExtractPlugin,
      new webpack.DefinePlugin({
          'process.env.NODE_ENV': '"'+TARGET+'"'
      })
    ]
  })
}
